<template>
  <div class="preview-container">
    <div class="preview-header">
      <h1>{{ documentTitle }}</h1>
      <button @click="goBack" class="back-button">返回编辑</button>
    </div>
    <div class="preview-content" v-html="documentContent"></div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { useRouter, useRoute } from 'vue-router'

const router = useRouter()
const route = useRoute()

const documentTitle = ref('未命名文档')
const documentContent = ref('')

// 返回编辑页面
const goBack = () => {
  const id = route.query.id as string
  if (id) {
    router.push(`/editor?id=${id}`)
  } else {
    router.push('/editor')
  }
}

// 加载文档
const loadDocument = async () => {
  const id = route.query.id as string
  if (!id) return
  
  try {
    const response = await fetch(`http://localhost:3000/api/documents/${id}`)  // 改为3000端口
    const data = await response.json()
    
    if (response.ok) {
      documentTitle.value = data.document.title
      documentContent.value = data.document.content
    } else {
      console.error('Failed to load document:', data.error)
    }
  } catch (err) {
    console.error('Load document error:', err)
  }
}

onMounted(() => {
  loadDocument()
})
</script>

<style scoped>
.preview-container {
  max-width: 800px;
  margin: 0 auto;
  padding: 20px;
}

.preview-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 2rem;
  padding-bottom: 1rem;
  border-bottom: 1px solid #eee;
}

.preview-header h1 {
  margin: 0;
  color: #333;
}

.back-button {
  padding: 0.5rem 1rem;
  background-color: #6c757d;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-size: 1rem;
}

.back-button:hover {
  background-color: #5a6268;
}

.preview-content {
  background-color: white;
  padding: 2rem;
  border-radius: 4px;
  box-shadow: 0 2px 4px rgba(0,0,0,0.1);
}

.preview-content h1 {
  font-size: 2rem;
  font-weight: bold;
  margin: 0 0 1rem 0;
  color: #333;
}

.preview-content h2 {
  font-size: 1.5rem;
  font-weight: bold;
  margin: 0 0 1rem 0;
  color: #333;
}

.preview-content p {
  margin: 0 0 1rem 0;
  line-height: 1.6;
  color: #555;
}

.preview-content strong {
  font-weight: bold;
}

.preview-content em {
  font-style: italic;
}

.preview-content ul {
  padding-left: 1.5rem;
  margin: 0 0 1rem 0;
}

.preview-content li {
  margin-bottom: 0.25rem;
}
</style>